from django.conf import settings
from django.contrib.auth.models import AbstractUser
from django.db import models

# Create your models here.
#创建用户模型类
from itsdangerous import BadData
from itsdangerous import TimedJSONWebSignatureSerializer

from meiduo_mall.utils.models import BaseModel


class User(AbstractUser):
    mobile = models.CharField(max_length=11,unique=True,verbose_name='手机号')
    email_active = models.BooleanField(verbose_name="邮箱激活",default=False)
    # 添加用户默认的收货地址字段
    default_address = models.ForeignKey('Address', related_name='users', null=True, blank=True,
                                        on_delete=models.SET_NULL, verbose_name='默认地址')
    class Meta:
        db_table = 'tb_users'
        verbose_name ='用户'
        verbose_name_plural = verbose_name


    def generate_verify_email_url(self):
        data = {
            "user_id": self.id,
            "email": self.email
        }

        serializer = TimedJSONWebSignatureSerializer(secret_key=settings.SECRET_KEY,expires_in=720000)

        token = serializer.dumps(data)
        # 前端端口8080
        verify_url = 'http://www.meiduo.site:8080/success_verify_email.html?token=' + token.decode()
        return verify_url

    @staticmethod
    def check_email_verify_token(token):
        """
        对加密用户信息进行解密：
        token: 加密用户的信息
        """
        serializer = TimedJSONWebSignatureSerializer(secret_key=settings.SECRET_KEY)

        try:
            data = serializer.loads(token)
        except BadData:
            # 解密失败
            return None
        else:
            # 解密成功
            user_id = data['user_id']
            email = data['email']

            try:
                user = User.objects.get(id=user_id, email=email)
            except User.DoesNotExist:
                return None
            else:
                return user

# 保存地址时的模型类
class Address(BaseModel):
    """
    用户地址
    """
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='addresses', verbose_name='用户')
    title = models.CharField(max_length=20, verbose_name='地址名称')
    receiver = models.CharField(max_length=20, verbose_name='收货人')
    province = models.ForeignKey('areas.Areas', related_name='province_id',on_delete=models.PROTECT, verbose_name='省')
    city = models.ForeignKey('areas.Areas',related_name='city_id', on_delete=models.PROTECT, verbose_name='市')
    district = models.ForeignKey('areas.Areas',related_name='district_id', on_delete=models.PROTECT, verbose_name='区')
    place = models.CharField(max_length=50, verbose_name='地址')
    mobile = models.CharField(max_length=11, verbose_name='手机')
    tel = models.CharField(max_length=20, null=True, blank=True, default='', verbose_name='固定电话')
    email = models.CharField(max_length=30, null=True, blank=True, default='', verbose_name='电子邮箱')
    is_deleted = models.BooleanField(default=False, verbose_name='逻辑删除')
    # 知识点：如果不给province,city,district设置related_name，获取city等信息时候会出现问题重复
    # 也就是说Areas.objects.get(name='南京市').address_set.all()查询的是市区以下的信息和查询是district的信息方法重复了
    # 默认地址设置不放再这里的原因是不然增删要２次,而user_id ,address_id相对应的话只需要一次
    class Meta:
        db_table = 'tb_address'
        verbose_name = '用户地址'
        verbose_name_plural = verbose_name

        # ordering表示在进行Address查询时，默认使用的排序方式,-表示从高到低
        ordering = ['-update_time']